// 性能优化工具 - 根据设备能力动态调整特效强度

export class PerformanceOptimizer {
  constructor() {
    this.deviceTier = this.detectDeviceTier()
  }

  // 检测设备性能等级
  detectDeviceTier() {
    const ua = navigator.userAgent.toLowerCase()
    const isMobile = /mobile|android|iphone|ipad|ipod/.test(ua)
    const cores = navigator.hardwareConcurrency || 2
    const memory = navigator.deviceMemory || 4

    // 低端设备
    if (isMobile && (cores < 4 || memory < 4)) {
      return 'low'
    }

    // 中端设备
    if (isMobile || cores < 8 || memory < 8) {
      return 'medium'
    }

    // 高端设备
    return 'high'
  }

  // 获取推荐的粒子数量
  getParticleCount(baseCount) {
    const multipliers = {
      low: 0.3,
      medium: 0.6,
      high: 1.0
    }
    return Math.floor(baseCount * multipliers[this.deviceTier])
  }

  // 是否启用高级特效
  shouldEnableAdvancedEffects() {
    return this.deviceTier !== 'low'
  }

  // 获取动画帧率目标
  getTargetFPS() {
    const fpsTargets = {
      low: 30,
      medium: 45,
      high: 60
    }
    return fpsTargets[this.deviceTier]
  }

  // FPS监控和自适应调整
  createFPSMonitor(callback) {
    let lastTime = performance.now()
    let frames = 0
    let fps = 60

    const measureFPS = () => {
      frames++
      const currentTime = performance.now()
      
      if (currentTime >= lastTime + 1000) {
        fps = Math.round((frames * 1000) / (currentTime - lastTime))
        frames = 0
        lastTime = currentTime
        
        // 如果FPS低于目标，回调通知降低质量
        const targetFPS = this.getTargetFPS()
        if (fps < targetFPS * 0.8) {
          callback({ fps, shouldReduce: true })
        } else {
          callback({ fps, shouldReduce: false })
        }
      }
      
      requestAnimationFrame(measureFPS)
    }

    measureFPS()
  }
}

export default new PerformanceOptimizer()

